package com.geqian.web.init;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
@ConditionalOnProperty(prefix = "spring.profiles", name = "active", havingValue = "dev")
public class ServerURLPrintRunner implements ApplicationRunner {

    @Value("${server.port}")
    private Integer serverPort;

    @Value("${server.servlet.context-path:}")
    private String contextPath;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        printServerURL();
    }


    public void printServerURL() {
        try {
            String networkIp = getNetworkIp();
            System.out.println();
            System.out.println("server running at:");
            System.out.println("- Local:   http://" + "localhost" + ":" + serverPort + contextPath);
            System.out.println("- Network: http://" + networkIp + ":" + serverPort + contextPath);
            System.out.println("- 接口文档: http://" + networkIp + ":" + serverPort + contextPath + "/doc.html");
            System.out.println();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    private String getLocalIp() throws UnknownHostException {
        InetAddress localhost = InetAddress.getLocalHost();
        return localhost.getHostAddress();
    }


    private String getNetworkIp() throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        if (inetAddress.isLoopbackAddress()) {
            // 如果本地IP是环回地址，则获取第一个非环回地址
            InetAddress[] allAddresses = InetAddress.getAllByName(inetAddress.getHostName());
            for (InetAddress address : allAddresses) {
                if (!address.isLoopbackAddress()) {
                    return address.getHostAddress();
                }
            }
        }
        return inetAddress.getHostAddress();
    }
}